/* eslint-disable no-param-reassign */
import qs from 'qs';
import pinia, { useUserStore } from '@/store';
import { IResData, IUserInfo } from '@/typings';
import { toAuthPage } from '@/utils/jump';

let isRefreshing = false; // 是否正在刷新的标记
let requests = []; // 重试队列
type CustomRequestOptions = UniApp.RequestOptions & { query?: Record<string, any> };

// 请求基地址
const baseURL = import.meta.env.VITE_SERVER_BASEURL;
// console.log(import.meta.env)

// 拦截器配置
const httpInterceptor = {
	// 拦截前触发
	invoke(options: CustomRequestOptions) {
		// 接口请求支持通过 query 参数配置 queryString
		if (options.query) {
			const queryStr = qs.stringify(options.query);
			if (options.url.includes('?')) {
				options.url += `&${queryStr}`;
			} else {
				options.url += `?${queryStr}`;
			}
		}

		// 1. 非 http 开头需拼接地址
		if (!options.url.startsWith('http')) {
			options.url = baseURL + options.url;
		}
		// 2. 请求超时
		options.timeout = 10000; // 10s
		// 3. 添加小程序端请求头标识
		options.header = {
			platform: 'mp-weixin', // 可选值与 uniapp 定义的平台一致，告诉后台来源
			'client-id': 'hubei_by_tea', // 教师端小程序
			...options.header,
		};
		// 4. 添加 token 请求头标识
		const userStore = useUserStore(pinia);
		const { token } = userStore.userInfo as unknown as IUserInfo;
		options.header.Authorization = token ? `${token}` : 'Bearer';
	},
};

// 拦截 request 请求
uni.addInterceptor('request', httpInterceptor);
// 拦截 uploadFile 文件上传
uni.addInterceptor('uploadFile', httpInterceptor);

export const http = <T>(options: CustomRequestOptions) => {
	// 1. 返回 Promise 对象
	return new Promise<IResData<T>>((resolve, reject) => {
		uni.request({
			...options,
			// 响应成功
			success(res) {
				const userStore = useUserStore(pinia);
				const data = res.data as IResData<T>;
				if (data.status_code === 401) {
					/* eslint-disable no-new */
					new Promise(() => {
						requests.push(() => {
							resolve(http({ ...options }));
						});
					});
					// 401错误  -> 清理用户信息
					userStore.clearUserInfo();

					if (!isRefreshing) {
						isRefreshing = true;
						// 调用获取token的方法

						return getLoginSilent()
							.then(() => {
								requests.forEach(cb => cb({ ...options }));
								requests = [];
								return false;
							})
							.catch(() => {
								uni.showModal({
									title: '提示',
									content: '登录状态已失效,请重新登录',
									showCancel: false,
									success(res) {
										if (res.confirm) {
											toAuthPage();
										}
									},
								});
							})
							.finally(() => {
								isRefreshing = false;
							});
					}
					return false;
				}
				if (data && data.status_code !== 200) {
					// 其他错误 -> 根据后端错误信息轻提示
					uni.showToast({
						icon: 'none',
						title: (res.data as IResData<T>).message || '请求错误',
					});
					// return reject(res);
				}
				return resolve(data);
			},
			// 响应失败
			fail(err) {
				console.log('err', err);
				uni.showToast({
					icon: 'none',
					title: '网络错误，换个网络试试',
				});
				return reject(err);
			},
		});
	});
};

const getLoginCode = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success(res) {
				if (res.code) {
					resolve(res);
				} else {
					reject(res);
				}
			},
			fail(err) {
				reject(err);
			},
		});
	});
};

export const getLoginSilent = async () => {
	const userStore = useUserStore(pinia);
	return new Promise<IResData<any>>((resolve, reject) => {
		getLoginCode()
			.then(async (res: { code: string }) => {
				uni.request({
					url: `${baseURL}/api/auth/login_silent_wx`,
					method: 'POST',
					data: { code: res.code },
					header: {
						platform: 'mp-weixin', // 可选值与 uniapp 定义的平台一致，告诉后台来源
						'client-id': 'hubei_by_stu', // 学生端小程序
					},
					success(login) {
						const data = login.data as IResData<any>;
						if (data.status_code === 200 && data.data) {
							//console.log('===>login', data.data);
							const default_student = data.data.default_student || {};
							userStore.setUserInfo({
								...default_student,
								token: data.data.token.token_type + data.data.token.access_token,
							});
							resolve(data);
						} else {
							reject(false);
						}
					},
					fail(err) {
						console.log('err', err);
						reject(false);
					},
				});
			})
			.catch(() => {
				reject(false);
			});
	});
};

export default http;
